#include<iostream>
#include<pthread.h>
#include<unistd.h>

using namespace std;

//电影厅有20张票
int ticket=1000;
pthread_mutex_t mutex;

class have
{
public:
    //默认开始没有票
    have(int cnt=0)
    :_cnt(cnt)
    {}

    int add()
    {
        return ++_cnt;
    }

public:
    int _cnt=0;
};

void *rob(void* i)
{
    have *ret=static_cast<have*>(i);
    //循环抢票
    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(ticket>0)  //如果有票就一直抢
        {
            ticket--;
            cout<<"现在的余票是 ： "<<ticket<<endl;
            ret->add();
        }
        else    
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
        pthread_mutex_unlock(&mutex);
        usleep(50);   //避免循环抢锁

    }
}

int main()
{
    //初始化锁
    pthread_mutex_init(&mutex,NULL);

    have a_h,b_h;

    //创建两个线程抢票
    pthread_t a,b;
    pthread_create(&a,NULL,rob,&a_h);
    pthread_create(&b,NULL,rob,&b_h);

    sleep(1);

    pthread_mutex_destroy(&mutex);

    //阻塞等待线程
    pthread_join(a,NULL);
    pthread_join(b,NULL);

    cout<<"a抢到"<<a_h._cnt<<"张票"<<endl;
    cout<<"b抢到"<<b_h._cnt<<"张票"<<endl;

    return 0;
}